//
//  LYSubjectViewController.m
//  artist
//
//  Created by Jay_Apple on 16/2/29.
//  Copyright © 2016年 viviyoo. All rights reserved.
//

#import "LYSubjectViewController.h"
#import "LYHomeViewController.h"
#import "LYMineViewController.h"
#import "LYDiscoverViewController.h"
#import "LYSubjectViewController.h"
#import "LYEArtistCell.h"

//#import "LYScreenBar.h"
#import "LYScreenBarSubject.h"

#import "LYSubjectListDBTool.h"
#import "LYChooseListView.h"
#import "LYVideoModel.h"
#import "LYCollectListModel.h"
#import "LYSearchBar.h"
#import "LYClassWebViewController.h"
#import "VVYLocationManager.h"

@interface LYSubjectViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>


@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, weak) LYChooseListView *chooseView;

@property (nonatomic, strong) LYSearchBar *searchBar;

@property (nonatomic, strong) UIBarButtonItem *searchItem;

@property (nonatomic, strong) UIBarButtonItem *cancelItem;

@property (nonatomic, assign) BOOL isSearching;

@property (nonatomic, strong) NSMutableArray *models;

@property (nonatomic, assign) NSInteger page;

//@property (nonatomic, weak) LYScreenBar *screenBar;
@property (nonatomic, weak) LYScreenBarSubject *screenBar;

@end

@implementation LYSubjectViewController


- (void)viewDidLoad{
    
    [super viewDidLoad];
    
    //初始化导航栏
    [self setUpNav];
    
    //初始化筛选栏
    [self setUpScreenBar];
    
    
    [self.tableView.mj_header beginRefreshing];
    
}

#pragma mark - 网络请求

/**
 *  请求新数据
 */
- (void)loadNewData{
    
    LYGetSubjectParameterModel *requestModel = [self getRequsetModelWithPage:@"1"];
    
    [LYRequestTool getSubjectListWithParmeterModel:requestModel success:^(NSArray<LYMyClassListModel *> *models) {
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer resetNoMoreData];
        self.models = [models mutableCopy];
        [self.tableView reloadData];
        self.page = 1;
        
        
    } failure:^(NSString *code, NSString *message) {
        [self.tableView.mj_header endRefreshing];
    }];
    
    
}
/**
 *  加载更多数据
 */
- (void)loadMoreData{
    
    NSString *page = [NSString stringWithFormat:@"%zd",self.page + 1];
    
    
    LYGetSubjectParameterModel *requestModel = [self getRequsetModelWithPage:page];
    
    [LYRequestTool getSubjectListWithParmeterModel:requestModel success:^(NSArray<LYMyClassListModel *> *models) {
        
        if (models.count == 0) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            return;
        }
        
        [self.tableView.mj_footer endRefreshing];
        
        [self.models addObjectsFromArray:models];;
        self.page++;
        [self.tableView reloadData];
        
        
    } failure:^(NSString *code, NSString *message) {
        [self.tableView.mj_footer endRefreshing];
    }];
    
}

#pragma mark - 上下拉刷新
/**
 *  下拉
 */
- (void)tableViewHeaderRefreshMethod:(VVYRefreshTableView *)tableView{
    
    [self loadNewData];
    
}

/**
 *  上拉
 */
- (void)tableViewfooterRefreshMethod:(VVYRefreshTableView *)tableView{
    
    [self loadMoreData];
    
}




#pragma mark - 懒加载

- (UIBarButtonItem *)searchItem{
    
    if (_searchItem == nil) {
        _searchItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"搜索-blue"] style:UIBarButtonItemStyleDone target:self action:@selector(search)];
    }
    return _searchItem;
}

- (UIBarButtonItem *)cancelItem{
    
    if (_cancelItem == nil) {
        _cancelItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(search)];
    }
    return _cancelItem;
}

- (LYSearchBar *)searchBar{
    
    if (_searchBar == nil) {
        LYSearchBar *searchBar = [[LYSearchBar alloc] init];
        searchBar.frame = CGRectMake(0, 0, CGFLOAT_MAX, 30);
        searchBar.placeholder = @"搜索科目，老师，课程，机构";
        [searchBar addTarget:self action:@selector(textfieldChange:) forControlEvents:UIControlEventEditingChanged];

        _searchBar = searchBar;
    }
    return _searchBar;
}


#pragma mark - 初始化
/**
 *  初始化导航栏
 */
- (void)setUpNav{
    
    self.navigationItem.rightBarButtonItem = self.searchItem;
    
}


/**
 *  初始化筛选栏
 */
- (void)setUpScreenBar{
    
    LYScreenBarSubject *screenBar = [LYScreenBarSubject viewForNib];
    
    screenBar.frame = CGRectMake(0, 0, LYScreenWidth, 40);
    
    __weak typeof(self) weakSelf = self;
    __weak typeof(screenBar) weakScreenBar = screenBar;
    [self.view addSubview:screenBar];
    
    screenBar.block = ^(SceenType type){
        
        switch (type) {
            case SceenTypeSub:
                
                if (weakSelf.chooseView) {
                    [weakSelf.chooseView dismiss];
                }else{
                    
                    weakSelf.chooseView = [LYChooseListView showOnView:weakSelf.tableView];
                    weakSelf.chooseView.block = ^(NSString *title){
                        if (title) {
                            weakScreenBar.subTitle = title;
                            [weakSelf.tableView.mj_header beginRefreshing];
                        }
                        [weakScreenBar backToNormal];
                    };
                }
                
                
                break;
                
            default:
                
                [weakSelf.chooseView dismiss];
                [weakSelf.tableView.mj_header beginRefreshing];
                
                break;
        }
        
    };
    
    self.screenBar = screenBar;
    
}

#pragma mark - tableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 80;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    LYMyClassListModel *model = self.models[indexPath.row];
    LYClassWebViewController *classWebVC = [LYClassWebViewController classWebVCWithID:model.Id];
    [self.navigationController pushViewController:classWebVC animated:YES];
    
}


#pragma mark - tableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.models.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellID = @"LYEArtistCell";
    LYEArtistCell *cell = [LYEArtistCell cellWithTableView:tableView andIndetifier:cellID];
    
    //model
    LYMyClassListModel *model = self.models[indexPath.row];
    cell.model = model;
    
    return cell;
    
}


#pragma mark - textFiled输入监听

- (void)textfieldChange:(UITextField *)textField{
    
    [self loadNewData];
    
}

#pragma mark - 按钮点击
- (void)search{
    
    //是否正在搜索
    if (self.isSearching) {//是(取消搜索操作)
        
        //修改rightItem
        self.navigationItem.rightBarButtonItem = self.searchItem;
        
        //修改titleView
        self.navigationItem.titleView = nil;
        
        //清除搜索关键词
        self.searchBar.text = @"";
        
        
        //重新刷新列表
        [self loadNewData];
        
        
    }else{//否(进入搜索)
        
        //修改rightItem
        self.navigationItem.rightBarButtonItem = self.cancelItem;
        
        //修改titleView
        self.navigationItem.titleView = self.searchBar;
        
        
        //弹出键盘
        [self.searchBar becomeFirstResponder];
        
    }
    
    
    //改变状态
    self.isSearching = !self.isSearching;
    
    
}

#pragma mark - 其他

- (LYGetSubjectParameterModel *)getRequsetModelWithPage:(NSString *)page{
    
    LYLocationInfo *locationInfo = [LYDataSourceManager sharedManager].locationInfo;
    
    NSString *subpath = nil;
    
    if (self.screenBar.subTitle) {
        subpath = [LYSubjectListDBTool getSubpathWithSubTitle:self.screenBar.subTitle];
    }
    
    
    LYGetSubjectParameterModel *model = [[LYGetSubjectParameterModel alloc] init];
    model.page = page;
    model.per_page = @"10";
    model.token = LYToken;
    model.subject_path = subpath;
    model.order = self.screenBar.orderType;
    model.keyword = self.searchBar.text;
    
    if (locationInfo) {
        model.lat = locationInfo.lat;
        model.lng = locationInfo.lng;
    }else{
        
        if(model.order ==  LYSubjectOrderTypeNear || model.order == LYSubjectOrderTypeFar){
            
        [MBProgressHUD showOnlyText:@"正在等待定位"];
        [[VVYLocationManager sharedManager] getLocationCityInfoSuccess:^(NSString *city, CLLocationCoordinate2D coordinate) {
            [[LYDataSourceManager sharedManager] setUpLocationInfo];
        } failure:^(NSString *error) {
            [MBProgressHUD showError:@"定位失败"];
        }];
        [self.tableView.mj_header endRefreshing];
        }
    }
    
    return model;
    
}

@end
